package com.xyy.ebattery.tcp.app;

import com.xyy.ebattery.tcp.app.config.NettyConfig;
import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.annotation.PreDestroy;



/**
 * @Description TODO
 * @author JIA BOYAN
 * date 2025/06/16  17.41
 */
@Component
public class NettyServer {
    private final EventLoopGroup bossGroup;
    private final EventLoopGroup workerGroup;
    private final ServerBootstrap bootstrap;
    private ChannelFuture channelFuture;

    @Autowired
    public NettyServer(NettyConfig config,
                       ChannelInitializer<SocketChannel> channelInitializer) {

        this.bossGroup = new NioEventLoopGroup(config.getBossThreads());
        this.workerGroup = new NioEventLoopGroup(config.getWorkerThreads());

        this.bootstrap = new ServerBootstrap()
                .group(bossGroup, workerGroup)
                .channel(NioServerSocketChannel.class)
                .option(ChannelOption.SO_BACKLOG, config.getBacklog())
                .childOption(ChannelOption.SO_KEEPALIVE, config.isKeepAlive())
                .childHandler(channelInitializer);
    }

    public void start(int port) throws InterruptedException {
        channelFuture = bootstrap.bind(port).sync();
        System.out.println("Netty server started on port: " + port);
    }

    @PreDestroy
    public void shutdown() {
        workerGroup.shutdownGracefully();
        bossGroup.shutdownGracefully();
        System.out.println("Netty server resources released");
    }
}